#!/bin/bash

# 此脚本需要在Canal节点执行，包括检测Canal进程状态、端口状态、错误日志（错误日志目前没有恢复策略，慎用）、zookeeper状态与端口

# 系统ID
system_id=$(cat config.cnf | grep SystemId | awk -F "=" '{print $2}')
# 告警存放文件夹
alert_dir=$(cat config.cnf | grep AlertDir | awk -F "=" '{print $2}')
# 告警缓存文件
alarm_file_tmp="canal_check_alarm.txt"
echo -n "" >${alarm_file_tmp}
# 本机ip
local_ip=`ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"`
# canal端口
admin_manager_port=$(cat config.cnf |grep CanalAdminManagerPort |awk -F "=" '{print $2}')
tcp_port=$(cat config.cnf |grep CanalTcpPort |awk -F "=" '{print $2}')
metric_port=$(cat config.cnf |grep CanalMetricPort |awk -F "=" '{print $2}')
deployer_port=$(cat config.cnf |grep CanalDeployerPort |awk -F "=" '{print $2}')
adapter_port=$(cat config.cnf |grep CanalAdapterPort |awk -F "=" '{print $2}')
execute_cycle=$(cat config.cnf | grep ExecuteCycle | awk -F "=" '{print $2}')


# canal组件运行状态监控
canal_status_check() {
    component_name=$1
    canal_status=$(ps -ef | grep ${component_name} | grep -v grep | grep -v canal_check | wc -l)
    # 检查状态是否为 active
    if [[ ${canal_status} == 0 ]]; then
        # 无进程进行告警
        ./gen_alarm.sh -g "应用进程监控" "${component_name}服务运行状态异常,IP:$(hostname -I)" 3 "${component_name}进程" "${component_name}_status" ${alarm_file_tmp}
    else
        # 状态正常且存在状态告警，则需要恢复告警
        ./gen_alarm.sh -r "应用进程监控" "${component_name}服务运行状态恢复正常,IP:$(hostname -I)" "${component_name}进程" "${component_name}_status" ${alarm_file_tmp}
		
		# 端口检查
		canal_port_check
    fi
}

# canal运行端口监控
canal_port_check() {
	for i in $admin_manager_port $tcp_port $metric_port $deployer_port $adapter_port; do
		port=$(netstat -nplt | grep ":${i} ")
		if [[ ${port} == '' ]]; then
			# 端口未监听，告警
			./gen_alarm.sh -g "端口状态" "canal服务端口[${i}]未监听,IP:$(hostname -I)" 3 "canal端口状态" "canle_port_${i}" ${alarm_file_tmp}
		else
			# 端口正常且存在告警，需要恢复告警
			./gen_alarm.sh -r "端口状态" "canal服务端口[${i}]恢复正常,IP:$(hostname -I)" "canal端口状态" "canle_port_${i}" ${alarm_file_tmp}
		fi
	done
}

while true; do
    holidays_date=$(cat config.cnf | grep Holidays | awk -F "=" '{print $2}' | sed "s/,/ /g")
	current_date=$(date +'%Y-%m-%d')
	echo $holidays_date | grep -o $current_date >> /dev/null
	if [[ $? -eq 0 ]]; then
		exit 0
	else
	    echo -n "" >${alarm_file_tmp}
		canal_status_check canal-admin
		canal_status_check canal-deployer
		# 将缓存告警放入告警文件夹
		./gen_alarm.sh -s ${alarm_file_tmp}
		sleep ${execute_cycle}
	fi
done